package com.itheima.controller;

import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    //将方法的返回值放到缓存当中          动态获取user中的id字段
    @CachePut(cacheNames = "userCach",key = "#user.id")//key的生成：userCache::(key中指定的值)
//    @CachePut(cacheNames = "userCach",key = "#result.id")//result关键字：对象导航 代表当前方法的返回值
//    @CachePut(cacheNames = "userCach",key = "#p0.id")//代表获取的是形参列表中的第几个参数
//    @CachePut(cacheNames = "userCach",key = "#a0.id")//代表获取的是形参列表中的第几个参数
//    @CachePut(cacheNames = "userCach",key = "#root.args[0].id")
    @PostMapping
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

    @CacheEvict(cacheNames = "userCach",key = "#id")//key的生成：userCache::10
    @DeleteMapping
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

    @CacheEvict(cacheNames = "userCach", allEntries = true)//删除所有的键值对
	@DeleteMapping("/delAll")
    public void deleteAll(){
        userMapper.deleteAll();
    }

    @Cacheable(cacheNames = "userCach",key = "#id")//key的生成：userCache::(key中指定的值)
    @GetMapping
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

}
